package com.game.springbootstart.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.game.springbootstart.DTO.AdminDTO;
import com.game.springbootstart.VO.AdminVO;
import com.game.springbootstart.VO.ChangePasswordRequest;
import com.game.springbootstart.annotation.AutoFill;
import com.game.springbootstart.config.QueryPageParam;
import com.game.springbootstart.config.Result;
import com.game.springbootstart.constant.JwtClaimsConstant;
import com.game.springbootstart.entity.Admin;
import com.game.springbootstart.enumeration.OperationType;
import com.game.springbootstart.properties.JwtProperties;
import com.game.springbootstart.service.IAdminService;
import com.game.springbootstart.utils.JwtUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 员工信息 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-02-09
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    private IAdminService adminService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation(value = "员工登录")
    public Result login(@RequestBody AdminDTO AdminDTO) {

        Admin admin = adminService.login(AdminDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, admin.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        AdminVO adminVO = AdminVO.builder()
                .id(admin.getId())
                .userName(admin.getUsername())
                .name(admin.getName())
                .token(token)
                .role(admin.getRole())
                .imgUrl(admin.getImgUrl())
                .build();

        return Result.success(adminVO);
    }

    @AutoFill(OperationType.INSERT)
    @PostMapping("/save")
    public Result save(@RequestBody Admin admin) {
        String password = admin.getPassword();
        password = passwordEncoder.encode(password);
        admin.setPassword(password);
        admin.setRole("用户");
        return Result.success(adminService.save(admin));
    }

    @GetMapping("/list")
    public Result listByName(@RequestParam Long id){
        return Result.success(adminService.listById(id));
    }


    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String username = (String)param.get("username");
        Page<Admin> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Admin::getUsername,username);
        IPage<Admin> result = adminService.page(page, queryWrapper);
        return Result.success(result.getRecords(), result.getTotal());
    }

    @PostMapping("/status")
    public Result changeStatus(@RequestBody Admin admin) {
        int status = admin.getStatus();
        if (status == 1) {
            admin.setStatus(0);
            return Result.success(adminService.updateById(admin));
        } else {
            admin.setStatus(1);
            return Result.success(adminService.updateById(admin));
        }
    }

    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody ChangePasswordRequest changePasswordRequest) {
        String currentUsername = changePasswordRequest.getUserName();
        Admin admin = adminService.getAdminByUsername(currentUsername);

        if (admin == null) {
            return Result.fail();
        }
        if(!admin.getPassword().equals(DigestUtils.md5DigestAsHex(changePasswordRequest.getOldPassword().getBytes()) )){
            return Result.fail();
        }


        // 更新新密码
        String newPassword = changePasswordRequest.getNewPassword();
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        admin.setPassword(newPassword);
        adminService.updateById(admin);

        return Result.success("密码修改成功");
    }

    @PostMapping("/saveOrMod")
    public Result saveOrUpdate(@RequestBody Admin admin) {
        if (admin.getId() == null) {
            return Result.success(adminService.updateById(admin));
        }
        return Result.success(adminService.updateById(admin));
    }

    @PostMapping("/insertImg")
    public Result insertImg(@RequestBody Admin admin) {
        Boolean flag = adminService.updateById(admin);
        if (flag) {
            return Result.success(flag);
        } else {
            return Result.fail();
        }
    }
}
